package com.bestom.hardwaretest.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import com.bestom.hardwaretest.File.FilesConstant;
import com.bestom.hardwaretest.R;
import com.bestom.hardwaretest.util.SharedPreferencesUtil;

public class SettingActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initView();
        updateData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
            case R.id.update:
                setEnabled(true);
                break;
            case R.id.save:
                new AlertDialog.Builder(this)
                        .setTitle("保存")
                        .setMessage("确定要保存修改吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            saveData();
                            updateData();
                            setEnabled(false);
                        })
                        .setNegativeButton("取消", null)
                        .show();
                break;
            case R.id.reset:
                new AlertDialog.Builder(this)
                        .setTitle("恢复默认")
                        .setMessage("确定要恢复默认数据吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            resetData();
                            updateData();
                            setEnabled(false);
                        })
                        .setNegativeButton("取消", null)
                        .show();
                break;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    /**保存数据*/
    private void saveData() {
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mLedPref,ledNode.getText().toString().trim());
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mIrPref,irNode.getText().toString().trim());
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mRelayPref,relayNode.getText().toString().trim());
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mBuzzerPref,buzzerNode.getText().toString().trim());
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mRadarPref,radarNode.getText().toString().trim());
    }

    /**恢复默认*/
    private void resetData() {
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mLedPref,FilesConstant.mLedDefaultPath);
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mIrPref,FilesConstant.mIrDefaultPath);
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mRelayPref,FilesConstant.mRelayDefaultPath);
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mBuzzerPref,FilesConstant.mBuzzerDefaultPath);
        SharedPreferencesUtil.getInstance().putValue(FilesConstant.mRadarPref,FilesConstant.mRadarDefaultPath);
    }

    /**更新视图*/
    private void updateData() {
        ledNode.setText((String) SharedPreferencesUtil.getInstance().getValue(FilesConstant.mLedPref,FilesConstant.mLedDefaultPath));
        irNode.setText((String) SharedPreferencesUtil.getInstance().getValue(FilesConstant.mIrPref,FilesConstant.mIrDefaultPath));
        relayNode.setText((String) SharedPreferencesUtil.getInstance().getValue(FilesConstant.mRelayPref,FilesConstant.mRelayDefaultPath));
        buzzerNode.setText((String) SharedPreferencesUtil.getInstance().getValue(FilesConstant.mBuzzerPref,FilesConstant.mBuzzerDefaultPath));
        radarNode.setText((String) SharedPreferencesUtil.getInstance().getValue(FilesConstant.mRadarPref,FilesConstant.mRadarDefaultPath));
    }

    /**设置是否可点击*/
    private void setEnabled(boolean b) {
        ledNode.setEnabled(b);
        irNode.setEnabled(b);
        relayNode.setEnabled(b);
        buzzerNode.setEnabled(b);
        radarNode.setEnabled(b);
        int color;
        if (b) color = Color.WHITE;
        else color = Color.parseColor("#09ebb3");
        ledNode.setTextColor(color);
        irNode.setTextColor(color);
        relayNode.setTextColor(color);
        buzzerNode.setTextColor(color);
        radarNode.setTextColor(color);
    }

    private EditText ledNode;
    private EditText irNode;
    private EditText relayNode;
    private EditText buzzerNode;
    private EditText radarNode;
    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("设置");
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        ledNode = findViewById(R.id.led_node);
        irNode = findViewById(R.id.ir_node);
        relayNode = findViewById(R.id.relay_node);
        buzzerNode = findViewById(R.id.buzzer_node);
        radarNode = findViewById(R.id.radar_node);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) return true;
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            // 点击的是输入框区域，保留点击EditText的事件
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }
}
